package com.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.constant.ProductConstant;
import com.common.utils.PageUtils;
import com.common.utils.Query;
import com.gulimall.product.dao.*;
import com.gulimall.product.entity.*;
import com.gulimall.product.service.AttrService;
import com.gulimall.product.service.CategoryService;
import com.gulimall.product.service.ProductAttrValueService;
import com.gulimall.product.vo.AttrGroupRelationVo;
import com.gulimall.product.vo.AttrRespVo;
import com.gulimall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);  //将attr对象的各个属性的值传到attrEntity对象中，前提是属性名要一一对应
        //1.保存数据
        this.save(attrEntity);          //在这里保存中也将自增的ID传回给对象attrEntity，在下面可以直接获取
        //2.创建关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()&&attr.getAttrGroupId()!=null) {             //如果是销售属性就不需要添加关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            //        System.out.println("attrEntity"+attrEntity);
            //        System.out.println("attr"+attr);
            relationDao.insert(relationEntity);
        }
    }
    //查询指定的数据

    @Override
    public PageUtils querySearch(Map<String, Object> params, Long catelogId, String saletype) {
        int type = saletype.equalsIgnoreCase("base") ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode();
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", type);
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        PageUtils pageUtils = new PageUtils(page);        //返回的页对象

        List<AttrEntity> records = page.getRecords();       //数据
        List<AttrRespVo> respVoList = records.stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            //如果是销售信息就不需要添加数据
            if (type == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
                //设置分组信息
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (relationEntity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(respVoList);
        //TODO 综合案例2
        return pageUtils;
    }

    /**
     * 根据分组ID获取所有的属性
     * @param groupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long groupId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        List<AttrAttrgroupRelationEntity> list = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", groupId));
        if(list==null||list.size()==0){
            return null;
        }
        List<Long> attrIds = list.stream().map((relation) -> {
            return relation.getAttrId();
        }).collect(Collectors.toList());
        if (attrIds != null || attrIds.size() != 0) {
            List<AttrEntity> attrList = this.listByIds(attrIds);
            return attrList;
        }
        return null;
    }

    /**
     * 获取可以连接的属性
     *
     * @param attrgroupId
     * @param params
     * @return
     */
    //TODO 未关联
    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        //获取当前分类category下的其他分组ID
        List<AttrGroupEntity> groupEntityList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        if (groupEntityList != null && groupEntityList.size() != 0) {
            List<Long> groupIds = groupEntityList.stream().map((groupEntity) -> {
                return groupEntity.getAttrGroupId();
            }).collect(Collectors.toList());
            //查找相同分类下的其他分组关联的属性（属性分为基本属性（规格参数）和销售属性（不参与和分组的关联））ID
            List<AttrAttrgroupRelationEntity> relationList
                    = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
            if (relationList != null && relationList.size() > 0) {
                List<Long> attrIds = relationList.stream().map((relation) -> {
                    return relation.getAttrId();
                }).collect(Collectors.toList());
                queryWrapper.notIn("attr_id", attrIds);      //添加相关条件
            }
        }
        queryWrapper.eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        String key = (String) params.get("key");
        if (key != null) {
            queryWrapper.and((query) -> {
                query.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> iPage = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        return new PageUtils(iPage);
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] relationEntities) {
        List<AttrAttrgroupRelationEntity> list = Arrays.asList(relationEntities).stream().map((relation) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(relation, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        relationDao.deleBatchRelation(list);
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity entity = baseMapper.selectById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(entity, attrRespVo);
        //设置分组名
        if (entity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", entity.getAttrId()));
            if (relationEntity != null) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //设置分类名
        CategoryEntity categoryEntity = categoryDao.selectById(entity.getCatelogId());
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        //设置分类树
        Long[] catelogPath = categoryService.findCatelogPath(entity.getCatelogId());
        attrRespVo.setCatelogPath(catelogPath);
        return attrRespVo;
    }

    @Override
    public void updatAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);
        //修改关联表
        if (attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()&&attrVo.getAttrGroupId()!=null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (count > 0) {
                relationDao.update(relationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            } else {
                relationDao.insert(relationEntity);
            }
        }
        if(attrVo.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode()){
            relationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrVo.getAttrId()));
        }
    }

}